# -*- coding: utf-8 -*-
# 用于计算文件的MD5值并验证是否与预期的MD5值匹配

import hashlib
import argparse

parser = argparse.ArgumentParser(description="Calculate and verify MD5 of a file")
parser.add_argument('-f','--filepath', help="Path of the file to be checked")
parser.add_argument('-e','--expectedmd5', help="Expected MD5 value of the file")

if not parser.parse_args().filepath or not parser.parse_args().expectedmd5:
    parser.print_help()
    exit(1)

def calculate_md5(file_path):
    md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        # 逐块读取文件内容并更新MD5哈希值
        for chunk in iter(lambda: f.read(4096), b""):
            md5.update(chunk)
    return md5.hexdigest()

def md5_verification(file_path, expected_md5):
    file_md5 = calculate_md5(file_path)
    return file_md5 == expected_md5

def color_print(text, color):
    # 用于在命令行中输出彩色文字
    print("\033[1;{}m{}\033[0m".format(31 + color, text))

file_path = parser.parse_args().filepath  # 文件路径
expected_md5 = parser.parse_args().expectedmd5  # 期望的MD5值
verification_result = md5_verification(file_path, expected_md5)
if verification_result:
    color_print("PASS", 1)
else:
    color_print("FAIL", 0)
